package controller

import (
	"fmt"
	"gin/common"
	"gin/model"
	"gin/response"
	"gin/util"
	"gin/util/getDate"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"strconv"
	"time"
)

type Sign struct {
	Id      int    `gorm:"column:id"`
	DateAdd string `gorm:"column:dateAdd"`
	Uid     int    `gorm:"column:uid"`
}

// GetSignList 签到记录
func GetSignList(ctx *gin.Context) {
	//获取本地location
	month := ctx.PostForm("month")
	start := month + "-01"
	end := getDate.GetMonthLastDay(month)
	Db := common.GetDB()
	user, _ := ctx.Get("user")
	var signDate []*Sign
	//转化所需模板
	Db.Debug().Table("cat_meal_user_sign").Where("uid=? dateAdd between ? and ?", user.(model.UserInfo).Uid, start, end).Find(&signDate)
	fmt.Println(signDate)
	for _, v := range signDate {
		//2021-11-05T00:00:00Z，多了后面的字符，截取或者替换
		v.DateAdd = util.Substr(v.DateAdd, 0, 10)
		//v.DateAdd=strings.Replace(v.DateAdd,"T00:00:00Z","",1)
	}
	response.Success(ctx, gin.H{"result": signDate}, "success")
}

// SignIn 签到
func SignIn(ctx *gin.Context) {
	Db := common.GetDB()
	user, _ := ctx.Get("user")
	now := time.Now()
	year, month, day := now.Date()
	dateAdd := strconv.Itoa(year) + "-" + strconv.Itoa(int(month)) + "-" + strconv.Itoa(day)
	var signDate Sign
	Db.Debug().Table("cat_meal_user_sign").Where("uid=?", user.(model.UserInfo).Uid).Where(" dateAdd = ?", dateAdd).First(&signDate)
	if len(signDate.DateAdd) > 0 {
		response.Fail(ctx, gin.H{}, "重复签到")
		return
	}
	err := Db.Transaction(func(tx *gorm.DB) error {
		var insert = Sign{
			Uid:     user.(model.UserInfo).Uid,
			DateAdd: util.DateFormatNotTime(0),
		}
		if err := Db.Debug().Table("cat_meal_user_sign").Create(&insert).Error; err != nil {
			// 返回任何错误都会回滚事务
			tx.Rollback()
			return err
		}
		err := model.ChangeScore(Db, user.(model.UserInfo), 1, 0)
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		util.LogError(err.Error())
		response.Fail(ctx, gin.H{}, err.Error())
		return
	}

	response.Success(ctx, gin.H{}, "success")
}
